package com.industry.framework.common.aspect;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.industry.framework.common.constant.Global;
import com.industry.framework.common.exception.ServiceException;
import com.industry.framework.common.utils.ServletUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author jsy
 * @description:Mapper分页参数注入切面
 * @date 2025/1/11 19:40
 */
@Aspect
@Order(10)
@Component
public class MapperAspect {
    /**
     * @description: 配置织入点
     * @author: jsy
     * @time: 2025/1/11 19:39
     */
    @Pointcut("execution(* com.industry.*..*.*Mapper.*(..))")
    public void mapperPointCut() {
    }

    /**
     * @description: Before增强：在目标方法被执行的时候织入增强 Mapper所有方法作为切入点
     * @author: jsy
     * @time: 2025/1/11 19:40
     */
    @Before("mapperPointCut()")
    public void mapperPointCut(JoinPoint joinPoint) {
        Object[] paramObjArray = joinPoint.getArgs();
        int pageNum = ServletUtil.getParameterToInt(Global.PAGE_NUM, Global.DEFAULT_PAGE_NUM);
        int pageSize = ServletUtil.getParameterToInt(Global.PAGE_SIZE, 80);
        // 遍历所有传入参数,赋值
        for (Object paramObj : paramObjArray) {
            if (paramObj instanceof IPage) {
                if (pageNum < 1 || pageSize < 1) {
                    throw new ServiceException("传递的分页参数有误!");
                }
                Page<?> page = ((Page<?>) paramObj);
                if(page != null){
                    if(page.getSize() <= 0L){
                        page.setSize(pageSize);
                    }
                    if(page.getCurrent() <= 0L){
                        page.setCurrent(pageNum);
                    }
                }
            }
        }
    }

}
